/**
 * @description address controller
 */

 const Address=require('../models/Address')

/**
 * 创建地址
 * @param {String} username //用户名
 * @param {Object} data     //地址的详细信息
 */

 async function createAddress(username,data) {
     const address =await Address.create({
         username,
         ...data,
     })
     return address
 }

/**
 * 获取地址列表
 * @param {String} username //用户名
 */

 async function getAddressList(username) {
     const list=await Address.find({username}).sort({updatedAt:-1})
     return list
 }

/**
 * 获取单个收货地址，根据id
 * @param {String} id  //id
 */

 async function getAddressById(id){
     const address=await Address.findById(id)
     return address
 }

/**
 * 更新单个收货地址，根据id，username
 * @param {String} id 
 * @param {String} username 
 * @param {Object} data 
 * @returns 
 */

async function updateAddress(id,username,data){
    const address =await Address.findOneAndUpdate({
        _id:id,
        username
    },{
        username,
        ...data
    },{
        new:true
    })
    return address
}

 module.exports={
     createAddress,
     getAddressList,
     getAddressById,
     updateAddress,
    }